package com.phpxiu.app.adapter.holder;

import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.text.SpannableStringBuilder;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.event.OnChatPhotoEvent;
import com.phpxiu.app.model.msg.C2CImageMsg;
import com.phpxiu.app.model.msg.C2CMsg;
import com.phpxiu.app.model.msg.C2CTextMsg;
import com.phpxiu.app.model.msg.C2CVoiceMsg;
import com.phpxiu.app.utils.FileManager;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.utils.VoiceManager;
import com.phpxiu.app.view.custom.FrescoImageView;
import com.tencent.TIMImage;
import com.tencent.TIMImageElem;
import com.tencent.TIMMessage;
import com.tencent.TIMSoundElem;
import com.tencent.TIMTextElem;
import com.tencent.TIMValueCallBack;
import com.tencent.bugly.imsdk.crashreport.CrashReport;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import de.greenrobot.event.EventBus;


/**
 * Created by 吴金洲 on 2016/8/24
 */
public class C2CChatMyMsgViewHolder implements View.OnClickListener {
    protected final static SpannableStringBuilder TXT=new SpannableStringBuilder();
    protected final static int maxPicWith=KKYUtil.dip2px(KKYApp.getInstance(),100);
    protected final static int maxPicHeight=KKYUtil.dip2px(KKYApp.getInstance(),150);
    protected C2CMsg c2cMsg;
    public TextView systemView;
    public View myView,friendView;
    public FrescoImageView myHeadView,friendHeadView,myPicView,friendPicView;
    public TextView myMsgView,friendMsgView;
    public LinearLayout myVoiceView,friendVoiceView;
    public TextView myVoiceTimeView,friendVoiceTimeView;
    public ImageView myVoiceSignView,friendVoiceSignView;
    protected AnimationDrawable myFrameAnimation,friendFrameAnimation,playAnim;
    private RelativeLayout stateBox;
    private ImageView progressView;
    private AnimationDrawable anim;
    protected boolean isDownloadingVoice=false;//正在下载语音
    private LinearLayout.LayoutParams params;
    protected RelativeLayout.LayoutParams rParams;
    public C2CChatMyMsgViewHolder(View itemView) {
        systemView=(TextView)itemView.findViewById(R.id.c2c_chat_msg_system_view);
        friendView=itemView.findViewById(R.id.c2c_chat_msg_friend_view);
        myView=itemView.findViewById(R.id.c2c_chat_msg_my_view);

        myHeadView=(FrescoImageView)itemView.findViewById(R.id.c2c_chat_msg_my_head_view);
        friendHeadView=(FrescoImageView)itemView.findViewById(R.id.c2c_chat_msg_friend_head_view);

        friendMsgView=(TextView)itemView.findViewById(R.id.c2c_chat_msg_friend_msg_view);
        myMsgView=(TextView)itemView.findViewById(R.id.c2c_chat_msg_my_msg_view);

        friendVoiceView=(LinearLayout)itemView.findViewById(R.id.c2c_chat_msg_friend_voice_view);
        friendVoiceView.setOnClickListener(this);
        myVoiceView=(LinearLayout)itemView.findViewById(R.id.c2c_chat_msg_my_voice_view);
        myVoiceView.setOnClickListener(this);
        friendVoiceTimeView=(TextView)itemView.findViewById(R.id.c2c_chat_msg_friend_voice_time_view);
        myVoiceTimeView=(TextView)itemView.findViewById(R.id.c2c_chat_msg_my_voice_time_view);
        friendVoiceSignView=(ImageView)itemView.findViewById(R.id.c2c_chat_msg_friend_voice_sign_view);
        friendFrameAnimation=(AnimationDrawable)friendVoiceSignView.getBackground();
        myVoiceSignView=(ImageView)itemView.findViewById(R.id.c2c_chat_msg_my_voice_sign_view);
        myFrameAnimation=(AnimationDrawable)myVoiceSignView.getBackground();

        friendPicView=(FrescoImageView)itemView.findViewById(R.id.c2c_chat_msg_friend_image_view);
        rParams=(RelativeLayout.LayoutParams)friendPicView.getLayoutParams();
        myPicView=(FrescoImageView)itemView.findViewById(R.id.c2c_chat_msg_my_image_view);
        myPicView.setOnClickListener(this);
        params=(LinearLayout.LayoutParams)myPicView.getLayoutParams();
        stateBox=(RelativeLayout)itemView.findViewById(R.id.my_msg_send_state_view);
        progressView=(ImageView)itemView.findViewById(R.id.my_msg_send_progress_view);//发送状态
        anim=(AnimationDrawable)progressView.getBackground();
    }

    /**
     * 显示消息时间
     * @param msg
     */
    protected void showMsgTime(C2CMsg msg){
        if(msg.isShowTime()){
            if(systemView.getVisibility()!=View.VISIBLE){
                systemView.setVisibility(View.VISIBLE);
            }
            systemView.setText(C2CMsg.getChatTimeStr(msg.getMessage().timestamp()));
        }else{
            if(systemView.getVisibility()==View.VISIBLE){
                systemView.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 显示我的消息
     * @param msg
     */
    public void showMyMsg(C2CMsg msg){
        //隐藏好友内容显示区域
        if(friendView.getVisibility()==View.VISIBLE){
            friendView.setVisibility(View.GONE);
        }
        //显示我的内容显示区域
        if(myView.getVisibility()!=View.VISIBLE){
            myView.setVisibility(View.VISIBLE);
        }
        if(msg instanceof C2CTextMsg){
            showMyTextMsg(msg);//显示文本消息
        }
        if(msg instanceof C2CVoiceMsg){//显示语音消息
            showMyVoiceMsg(msg);
        }
        if(msg instanceof C2CImageMsg){//显示图片消息
            showMyImageMsg(msg);
        }
    }

    /**
     * 显示我发送的文本、表情消息
     * @param msg
     */
    private void showMyTextMsg(C2CMsg msg){
        TXT.clear();
        if(stateBox.getVisibility()==View.VISIBLE){
            stateBox.setVisibility(View.INVISIBLE);
        }
        //隐藏显示的语音消息内容
        if(myVoiceView.getVisibility()==View.VISIBLE){
            myVoiceView.setVisibility(View.GONE);
        }
        //隐藏显示的图片消息内容
        if(myPicView.getVisibility()==View.VISIBLE){
            myPicView.setVisibility(View.GONE);
        }
        if(myMsgView.getVisibility()!=View.VISIBLE){
            myMsgView.setVisibility(View.VISIBLE);
        }
        TIMMessage timMessage=msg.getMessage();
        TIMTextElem textElem=null;
        for (int i=0;i<timMessage.getElementCount();i++){
            textElem = (TIMTextElem) timMessage.getElement(i);
            TXT.append(textElem.getText());
        }
        myMsgView.setText(TXT);
    }

    /**
     * 显示我发送的语音消息
     * @param msg
     */
    private void showMyVoiceMsg(C2CMsg msg){
        //隐藏显示的图片消息内容
        if(myPicView.getVisibility()==View.VISIBLE){
            myPicView.setVisibility(View.GONE);
        }
        if(myMsgView.getVisibility()==View.VISIBLE){
            myMsgView.setVisibility(View.GONE);
        }
        if(myVoiceView.getVisibility()!=View.VISIBLE){
            myVoiceView.setVisibility(View.VISIBLE);
        }
        TIMMessage message=msg.getMessage();
        TIMSoundElem voice=(TIMSoundElem) message.getElement(0);
        switch (message.status()) {
            case Sending:
                onSending();
                break;
            case SendSucc:
                onSendSuccess();
                break;
        }
        myVoiceTimeView.setText(String.valueOf(voice.getDuration())+"’");
    }

    /**
     * 显示我的图片
     * @param msg
     */
    private void showMyImageMsg(C2CMsg msg){
        if(myMsgView.getVisibility()==View.VISIBLE){
            myMsgView.setVisibility(View.GONE);
        }
        if(myVoiceView.getVisibility()==View.VISIBLE){
            myVoiceView.setVisibility(View.GONE);
        }
        if(myPicView.getVisibility()!=View.VISIBLE){
            myPicView.setVisibility(View.VISIBLE);
        }
        TIMMessage message=msg.getMessage();
        TIMImageElem elem = (TIMImageElem) message.getElement(0);
        int w=maxPicWith;
        int h=maxPicHeight;
        for(final TIMImage image : elem.getImageList()) {
            w=(int)Math.min(w,image.getWidth());
            h=(int)Math.min(h,image.getHeight());
        }
        File file=new File(elem.getPath());
        if(file.exists()&&file.isFile()){
            params.width=w;
            params.height=h;
            myPicView.setLayoutParams(params);
            myPicView.setImageURI(Uri.fromFile(file));
        }else{
            myPicView.setImageURI(Uri.parse("res:///"+R.drawable.def_user_icon));
        }
        myPicView.setTag(file.getPath());
        switch (message.status()){
            case Sending:
                onSending();
                break;
            case SendSucc:
                onSendSuccess();
                break;
        }
    }

    /**
     * 发送状态
     */
    private void onSending(){
        if(stateBox.getVisibility()!=View.VISIBLE){
            stateBox.setVisibility(View.VISIBLE);
        }
        anim.start();
    }

    /**
     * 消息发送成功
     */
    public void onSendSuccess(){
        if(stateBox.getVisibility()==View.VISIBLE){
            stateBox.setVisibility(View.INVISIBLE);
        }
        anim.stop();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.c2c_chat_msg_friend_voice_view:
            case R.id.c2c_chat_msg_my_voice_view:
                playAudio();
                break;
            case R.id.c2c_chat_msg_my_image_view:
            case R.id.c2c_chat_msg_friend_image_view:
                if(v.getTag()!=null){
                    KKYUtil.log("预览图片："+v.getTag().toString());
                    String uri=v.getTag().toString();
                    if(uri.startsWith("http")){
                        EventBus.getDefault().post(new OnChatPhotoEvent(Uri.parse(uri),uri));
                    }else{
                        EventBus.getDefault().post(new OnChatPhotoEvent(Uri.parse("file:///"+uri),null));
                    }

                }
                break;
            default:
                break;
        }
    }

    /**
     * 阅读语音
     */
    private void playAudio() {
        try {
            TIMMessage message=c2cMsg.getMessage();
            final TIMSoundElem elem = (TIMSoundElem) message.getElement(0);
            if (FileManager.isCacheFileExist(elem.getUuid())){
                playAudio(new File(FileManager.getCacheFilePath(elem.getUuid())));
                return;
            }
            if(isDownloadingVoice){
                return;
            }
            isDownloadingVoice=true;
            elem.getSound(new TIMValueCallBack<byte[]>() {
                @Override
                public void onError(int i, String s) {
                    KKYUtil.log("播放语音出错："+i+"--"+s);
                    isDownloadingVoice=false;
                }
                @Override
                public void onSuccess(byte[] bytes) {
                    FileManager.createFile(bytes, elem.getUuid());
                    playAudio(new File(FileManager.getCacheFilePath(elem.getUuid())));
                    isDownloadingVoice=false;
                }
            });
        }catch (NullPointerException e){
            isDownloadingVoice=false;
            CrashReport.postCatchedException(e);
        }
    }

    private void playAudio(File file){
        try {
            FileInputStream fis = new FileInputStream(file);
            VoiceManager.getInstance().play(fis);
            playAnim.start();
            VoiceManager.getInstance().setEventListener(new VoiceManager.OnVoiceEventListener() {
                @Override
                public void onVoiceStop() {
                    KKYUtil.log("播放语音动画完成");
                    playAnim.stop();
                    playAnim.selectDrawable(0);
                }
            });
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

